package fanshe;

import java.io.FileReader;
import java.net.URL;
import java.util.List;

import javax.management.StringValueExp;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ceshi {
	public static void main(String[] args) throws ScriptException, Exception {
		ScriptEngineManager sen=new ScriptEngineManager();
		ScriptEngine engie=sen.getEngineByName("javascript");
		engie.put("msg", "asdafah");
		String str="var user= {name:'gaoqi',age:18,school:['qinghua','beijing']};";
		str += "print(user.name);";
		engie.eval(str);
		engie.eval("msg='asdaf';");
		System.out.println(engie.get("msg"));
		System.out.println("**********");
		//定义函数
		engie.eval("function add(a,b){var sum=a+b;return sum;}");
		//取得调用接口
		Invocable jsk=(Invocable) engie;
		//执行脚本中定义的方法
		Object r=jsk.invokeFunction("add", new Object[] {13,20});
		System.out.println(r);
//		String jsc="var list = java.util.Arrays.asList([\"123\",\"321\",\"213\"])";
//		engie.eval(jsc);
//		List<String> l=	(List<String>) engie.get("list");
//		for (String string : l) {
//			System.out.print(string);
//		}
//		//执行jswenjian
		URL url=ceshi.class.getClassLoader().getResource("a.js");
		FileReader fr=new FileReader(url.getPath());
		engie.eval(fr);
		fr.close();
		
	}
}
